package com.evan.review.ipc;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Process;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.evan.review.R;

import java.util.List;

/**
 * 展示Android进程基础知识
 * 包括进程的概念、类型、创建方式和获取进程信息
 */
public class ProcessBasicActivity extends AppCompatActivity {
    private static final String TAG = "ProcessBasic";

    private TextView tvProcessInfo;
    private TextView tvProcessList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_process_basic);

        tvProcessInfo = findViewById(R.id.tv_process_info);
        tvProcessList = findViewById(R.id.tv_process_list);

        // 显示当前进程信息
        displayCurrentProcessInfo();

        // 创建新进程按钮
        Button btnCreateProcess = findViewById(R.id.btn_create_process);
        btnCreateProcess.setOnClickListener(v -> {
            // 启动在AndroidManifest中声明为独立进程的Activity
            Intent intent = new Intent(this, RemoteProcessActivity.class);
            startActivity(intent);
        });

        // 获取进程列表按钮
        Button btnGetProcessList = findViewById(R.id.btn_get_process_list);
        btnGetProcessList.setOnClickListener(v -> {
            displayProcessList();
        });

        // 进程优先级按钮
        Button btnProcessPriority = findViewById(R.id.btn_process_priority);
        btnProcessPriority.setOnClickListener(v -> {
            showProcessPriorityInfo();
        });

        // 设置进程优先级
        Button btnSetPriority = findViewById(R.id.btn_set_priority);
        btnSetPriority.setOnClickListener(v -> {
            setProcessPriority();
        });
        
        // 关于进程信息获取
        Button btnAboutProcess = findViewById(R.id.btn_about_process);
        btnAboutProcess.setOnClickListener(v -> {
            showAboutProcessDialog();
        });
    }

    // 显示当前进程信息
    private void displayCurrentProcessInfo() {
        int pid = Process.myPid();
        int uid = Process.myUid();
        int tid = Process.myTid();
        String processName = getProcessName(this, pid);

        StringBuilder info = new StringBuilder();
        info.append("当前进程信息：\n\n");
        info.append("进程ID (PID): ").append(pid).append("\n");
        info.append("用户ID (UID): ").append(uid).append("\n");
        info.append("线程ID (TID): ").append(tid).append("\n");
        info.append("进程名称: ").append(processName).append("\n");
        info.append("应用包名: ").append(getPackageName()).append("\n");

        tvProcessInfo.setText(info.toString());
    }

    // 显示系统中当前应用的进程列表
    private void displayProcessList() {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processes = am.getRunningAppProcesses();

        StringBuilder processList = new StringBuilder();
        processList.append("当前应用的进程列表：\n\n");

        if (processes != null) {
            for (ActivityManager.RunningAppProcessInfo process : processes) {
                if (process.processName.startsWith(getPackageName())) {
                    processList.append("进程名: ").append(process.processName).append("\n");
                    processList.append("PID: ").append(process.pid).append("\n");
                    processList.append("重要性: ").append(getImportanceString(process.importance)).append("\n\n");
                }
            }
        } else {
            processList.append("无法获取进程列表信息");
        }

        tvProcessList.setText(processList.toString());
    }

    // 根据PID获取进程名称
    private String getProcessName(Context context, int pid) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processes = am.getRunningAppProcesses();
        if (processes != null) {
            for (ActivityManager.RunningAppProcessInfo process : processes) {
                if (process.pid == pid) {
                    return process.processName;
                }
            }
        }
        return "未知进程";
    }

    // 根据importance值返回对应的描述
    private String getImportanceString(int importance) {
        switch (importance) {
            case ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND:
                return "前台进程 (IMPORTANCE_FOREGROUND)";
            case ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE:
                return "前台服务 (IMPORTANCE_FOREGROUND_SERVICE)";
            case ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE:
                return "可见进程 (IMPORTANCE_VISIBLE)";
            case ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE:
                return "可感知进程 (IMPORTANCE_PERCEPTIBLE)";
            case ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE:
                return "服务进程 (IMPORTANCE_SERVICE)";
            case ActivityManager.RunningAppProcessInfo.IMPORTANCE_TOP_SLEEPING:
                return "顶部休眠进程 (IMPORTANCE_TOP_SLEEPING)";
            case ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED:
                return "缓存进程 (IMPORTANCE_CACHED)";
            case ActivityManager.RunningAppProcessInfo.IMPORTANCE_EMPTY:
                return "空进程 (IMPORTANCE_EMPTY)";
            case ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE:
                return "消失进程 (IMPORTANCE_GONE)";
            default:
                return "未知 (" + importance + ")";
        }
    }

    // 显示进程优先级信息
    private void showProcessPriorityInfo() {
        StringBuilder info = new StringBuilder();
        info.append("Android进程优先级(由高到低)：\n\n");
        info.append("1. 前台进程(Foreground Process)：\n");
        info.append("   - 用户正在交互的Activity\n");
        info.append("   - 绑定到前台Activity的Service\n");
        info.append("   - 调用了startForeground()的Service\n");
        info.append("   - 正在执行生命周期回调的组件\n\n");

        info.append("2. 可见进程(Visible Process)：\n");
        info.append("   - 有可见但非前台的Activity\n");
        info.append("   - 绑定到可见Activity的Service\n\n");

        info.append("3. 服务进程(Service Process)：\n");
        info.append("   - 通过startService()启动的后台服务\n\n");

        info.append("4. 后台进程(Background Process)：\n");
        info.append("   - 不可见的Activity (onStop后)\n");
        info.append("   - 系统内存不足时可能被回收\n\n");

        info.append("5. 空进程(Empty Process)：\n");
        info.append("   - 不再包含任何活动组件的进程\n");
        info.append("   - 仅作为缓存，随时可能被终止\n\n");

        info.append("注意：当系统内存不足时，会按优先级从低到高依次回收进程");

        tvProcessList.setText(info.toString());
    }

    // 设置当前进程优先级
    private void setProcessPriority() {
        // 注意：这需要特定权限，普通应用无法随意设置进程优先级
        // 这里仅作为演示
        try {
            // 设置进程优先级，值越小优先级越高
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            tvProcessInfo.setText("已尝试将当前线程优先级设置为THREAD_PRIORITY_BACKGROUND\n" +
                    "注意：实际修改需要特定权限，普通应用能修改的范围有限。\n\n" +
                    "当前线程优先级: " + Process.getThreadPriority(Process.myTid()));
        } catch (Exception e) {
            tvProcessInfo.setText("设置优先级失败: " + e.getMessage());
        }
    }

    // 显示关于进程信息的对话框
    private void showAboutProcessDialog() {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("Android进程知识")
                .setMessage("Android进程基础：\n\n" +
                        "1. 每个应用默认运行在自己的Linux进程中\n\n" +
                        "2. 进程创建方式：\n" +
                        "   - 应用启动时自动创建\n" +
                        "   - 在AndroidManifest中为组件指定android:process属性\n" +
                        "   - 通过Native代码fork()创建(需要特殊权限)\n\n" +
                        "3. 进程命名规则：\n" +
                        "   - 默认应用包名作为进程名\n" +
                        "   - \":\"开头表示私有进程\n" +
                        "   - 其他名称表示全局进程\n\n" +
                        "4. 面试要点：\n" +
                        "   - 理解进程和应用的关系\n" +
                        "   - 掌握进程优先级和回收机制\n" +
                        "   - 了解多进程带来的问题(如单例失效、静态变量不共享等)\n" +
                        "   - 跨进程通信的实现方式")
                .setPositiveButton("了解", null)
                .show();
    }
} 